--
-- Author: zhouzhanglin
-- Date: 2014-10-09 22:55:01
--
---------------------------------------------
----@module ext.ui.Image  UI图片
---------------------------------------------
local Image = class("Image",require("ext.ui.Component"))

Image.SCALE_MODE_NO_SCALE = "noScale"
Image.SCALE_MODE_EXACT_FIT = "exactFit" --根据最大适应，有黑边，等比缩放，不会变形
Image.SCALE_MODE_NO_BORDER = "noBorder" --根据最小适应，无黑边，等比缩放，不会变形
Image.SCALE_MODE_SHOW_ALL = "showAll" --缩放显示，会变形


---------------------------------------------
----构造函数
----@function [parent=#ext.ui.Image]  ctor
----@param #string filename 图片名称，如果前面加#,从cacheFrame中找
---------------------------------------------
function Image:ctor(filename)
    Image.super.ctor(self)

    if filename==nil then
        self._sp = display.newSprite()
    else
        if type(filename)=="string" then
            self._sp = display.newSprite(filename)
        else
            self._sp = filename
        end
    end
    self:addChild(self._sp)
end

function Image:setFilename(filename)
    if self._sp == nil then 
        self:removeChild(self._sp)
    end
    self._sp = display.newSprite(filename)
    self:addChild(self._sp)
end

function Image:setScaleMode( mode , size )
    if self._sp == nil then return end

    if mode ~= Image.SCALE_MODE_NO_SCALE then
        assert(size,"size 不能为nil")
    end

    if mode==Image.SCALE_MODE_NO_SCALE then
        self._sp:setScale(1)
    elseif mode == Image.SCALE_MODE_NO_BORDER then
        local contentSize = self._sp:getContentSize()
        local rx,ry =size.width/contentSize.width , size.height/contentSize.height
        if rx<ry then
            self._sp:setScale(ry)
        else
            self._sp:setScale(rx)
        end
    elseif mode == Image.SCALE_MODE_EXACT_FIT then
        local contentSize = self._sp:getContentSize()
        local rx,ry =size.width/contentSize.width , size.height/contentSize.height
        if rx>ry then
            self._sp:setScale(ry)
        else
            self._sp:setScale(rx)
        end
    elseif mode == Image.SCALE_MODE_SHOW_ALL then
        local contentSize = self._sp:getContentSize()
        self._sp:setScaleX( size.width/contentSize.width)
        self._sp:setScaleY(  size.height/contentSize.height)
    end
end

---------------------------------------------
----返回此Image的SpriteFrame
----@function [parent=#ext.ui.Image] getSpriteFrame
----@return #cc.SpriteFrame 返回SpriteFrame
---------------------------------------------
function Image:getSpriteFrame()
    return self._sp:getSpriteFrame()
end

function Image:dispose()
    Image.super.dispose(self)
    self._sp = nil
end

return Image